<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入货号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签名称" prop="labelName">
        <el-input
          v-model="queryParams.labelName"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="上架状态" prop="listStatus" v-if="isAdmin">
        <el-select v-model="queryParams.listStatus" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in listStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:goodsInfo:add']"  v-if="isAdmin"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:goodsInfo:edit']" v-if="isAdmin"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:goodsInfo:remove']" v-if="isAdmin"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:goodsInfo:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="exportGoodsInfoExcel()" v-if="isAdmin">批量导入</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button type="warning" plain @click="addShopCartBatch()">加入购物车</el-button>

      </el-col>-->


      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsInfoList" @selection-change="handleSelectionChange" @row-click="rowClick">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="商品图片" align="center" prop="goodsCoverImg" width="150px" fixed class="el-image-viewer_wrapper">
        <template #default="scope">
          <el-image
              @click.stop
              style="width: 100px; height: 100px"
              :key="scope.row.id"
              :src="scope.row.goodsCoverImg"
              :preview-teleported="true"
              :preview-src-list="[scope.row.goodsCoverImg]">
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="商品编码" align="center" prop="code" min-width="200"/>
      <el-table-column label="货号" align="center" prop="number" min-width="200"/>
      <el-table-column label="商品名称" align="center" prop="name" min-width="200"/>
      <el-table-column label="物料名称" align="center" prop="materialName" min-width="200"/>
      <el-table-column label="规格" align="center" prop="specs" min-width="100"/>
      <el-table-column label="价格" align="center" prop="price" min-width="100"/>
      <el-table-column label="重量" align="center" prop="weight" min-width="100" />
      <el-table-column label="品牌名称" align="center" prop="brandName" min-width="150"/>
      <el-table-column label="分类名称" align="center" prop="categoryName" min-width="150"/>
      <el-table-column label="标签名称" align="center" prop="labelName" min-width="150"/>
      <el-table-column label="条码" align="center" prop="barCode" min-width="150"/>
      <el-table-column label="单位" align="center" prop="unit" min-width="150"/>

      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width"
                       fixed="right" class="el-image-viewer_wrapper">
        <template #default="scope">
          <el-button link type="primary" @click.stop="openDetail(scope.row.id)">详情</el-button>
<!--          <el-button link type="primary"  @click="addShopCart(scope.row)">加购物车</el-button>-->
          <el-button link type="primary" @click.stop="downLoadImg(scope.row)">素材下载</el-button>

          <el-button link type="primary" @click.stop="goodsChangeRecord(scope.row)">修改记录</el-button>
<!--          <el-button link type="primary" @click="imgZipDownLoad(scope.row)">素材下载</el-button>-->

          <el-button link type="primary" @click.stop="goodsOperate(scope.row, 'down')" v-if="scope.row.listStatus === 1 && isAdmin">下架</el-button>
          <el-button link type="primary" @click.stop="goodsOperate(scope.row, 'up')" v-if="scope.row.listStatus === 2 && isAdmin">上架</el-button>


        </template>
      </el-table-column>

    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="65%" append-to-body>
      <el-form ref="goodsInfoRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="头像图" prop="goodsCoverImgList" style="margin-left: 30px">
          <el-upload
            class="upload-demo"
            list-type="picture-card"
            :action="uploadImgServerMaster"
            accept="jpg,jpeg,png"
            :headers="{ token: token }"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess"
            :on-remove="handleRemove"
            :on-preview="handlePictureCardPreview"
            :limit="100"
            :multiple = "true"
            :file-list="fileList">
             <span class="plus-icon">+</span>
          </el-upload>
        </el-form-item>

        <el-form-item label="详情图" prop="goodsDetailImgList" style="margin-left: 30px">
          <el-upload
              class="upload-demo"
              list-type="picture-card"
              :action="uploadImgServerDetail"
              accept="jpg,jpeg,png"
              :headers="{ tokenDetail: token }"
              :before-upload="handleBeforeUploadDetail"
              :on-success="handleUrlSuccessDetail"
              :on-remove="handleRemoveDetail"
              :on-preview="handlePictureCardPreview"
              :limit="100"
              :multiple = "true"
              :file-list="detailFileList">
            <span class="plus-icon">+</span>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品编码" prop="code" style="margin-left: 30px">
          <el-input v-model="form.code" placeholder="请输入商品编码" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="商品货号" prop="number" style="margin-left: 30px">
          <el-input v-model="form.number" placeholder="请输入货号" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="name" style="margin-left: 30px">
          <el-input v-model="form.name" placeholder="请输入产品名称" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName" style="margin-left: 30px">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="商品规格" prop="specs" style="margin-left: 30px">
          <el-input v-model="form.specs" placeholder="请输入规格" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName" style="margin-left: 30px">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice" style="margin-left: 30px">
          <el-input v-model="form.costPrice" type="number" placeholder="请输入成本价" style="width: 100%; margin-right: 10px" @blur="handleCostPrice(form.costPrice)"/>
        </el-form-item>
        <el-form-item label="比价链接" prop="priceUrl" style="margin-left: 30px">
          <el-input v-model="form.priceUrl" placeholder="请输入比价链接" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="商品税率" prop="taxRate" style="margin-left: 30px">
          <el-input v-model="form.taxRate" type="number" placeholder="请输入税率" style="width: 95%; margin-right: 10px"></el-input>
          <span style="font-size: 23px">%</span>
        </el-form-item>
        <el-form-item label="税收编码" prop="taxCode" style="margin-left: 30px">
          <el-input v-model="form.taxCode" placeholder="请输入税收编码" style="width: 100%; margin-right: 10px"/>
        </el-form-item>

        <!-- <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item> -->

       <el-form-item label="商品价格" prop="price" style="margin-left: 30px">
            <el-row type="flex" >
              <el-col v-for = "(item, index) in merchantLevelArr " :key="index" style="margin-top: 10px">
                <span>{{ item.name }}商户：</span>
                <el-input v-model="item.price" style="width: 40%" type= "number" placeholder="请输入价格" @blur="handlePrice(item.price, index, item.id, item.name,item)" />
                <span style="margin-left: 20px">利润率：</span>
                <el-input v-model="item.profitRate" style="width: 40%" type= "number" disabled/><span style="font-size: 18px"> %</span>
              </el-col>
            </el-row>
        </el-form-item>

        <el-form-item label="活动价格" style="margin-left: 30px">
          <el-table :data="form.businessGoodsActivityPrices">
            <el-table-column label="商户" align="center" prop="merchantName" >
              <template #default="scope">
                <el-select filterable clearable v-model="scope.row.merchantName" collapse-tags placeholder="请选择">
                  <el-option v-for="item in merchantArr" :key="item.account" :label="item.account" :value="item.account" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="价格" align="center" prop="price" >
              <template #default="scope">
                <el-input v-model="scope.row.price" placeholder="请输入价格" />
              </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" prop="beginTimeStr" >
              <template #default="scope">
<!--                <el-input v-model="scope.row.beginTime" placeholder="请输入开始时间" />-->
                <el-date-picker
                    v-model="scope.row.beginTimeStr"
                    type="datetime"
                    style="width: 100%"
                    placeholder="请输入开始时间">
                </el-date-picker>
              </template>
            </el-table-column>

            <el-table-column label="结束时间" align="center" prop="endTimeStr" >
              <template #default="scope">
<!--                <el-input v-model="scope.row.endTime" placeholder="请输入结束时间" />-->
                <el-date-picker
                    v-model="scope.row.endTimeStr"
                    type="datetime"
                    style="width: 100%"
                    placeholder="请输入结束时间">
                </el-date-picker>

              </template>
            </el-table-column>
            <el-table-column label="" align="center">
              <template #default="scope">
                <el-button type="primary" :icon="Plus" plain circle @click="handleAddCol()" />
                <el-button v-if="scope.$index > 0" type="danger" :icon="Delete" plain circle @click="handleDeleteCol(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
<!--            <el-button link type="primary" @click="goodsActivityPriceDetail(form.id)">价格详情</el-button>-->
        </el-form-item>

        <el-form-item label="商品重量" prop="weight" style="margin-left: 30px">
          <el-input v-model="form.weight" type="number" placeholder="请输入重量" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName" style="margin-left: 30px">
          <template #default="scope">
            <el-select v-model="form.templateName" size="small" style="width: 100%; margin-right: 10px" filterable clearable @change="templateChange(form.templateName)">
              <el-option v-for="item in templateArr" :key="item.name" :label="item.name" :value="item.name" />
              <el-input v-model="form.templateId" hidden />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="品牌名称" prop="brandName" style="margin-left: 30px">
          <template #default="scope">
            <el-select v-model="form.brandName" size="small" style="width: 100%; margin-right: 10px" filterable clearable @change="brandChange(form.brandName)">
              <el-option v-for="item in brandArr" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName" style="margin-left: 30px">
          <template #default="scope">
            <el-select v-model="form.categoryName" size="small" style="width: 100%; margin-right: 10px" filterable clearable @change="categoryChange(form.categoryName)">
              <el-option v-for="item in categoryArr" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="标签名称" prop="labelName" style="margin-left: 30px">
          <template #default="scope">
            <el-select v-model="form.labelName" size="small" style="width: 100%; margin-right: 10px" filterable clearable @change="labelChange(form.labelName)">
              <el-option v-for="item in labelArr" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="商品条码" prop="barCode" style="margin-left: 30px">
          <el-input v-model="form.barCode" placeholder="请输入条码" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
        <el-form-item label="商品单位" prop="unit" style="margin-left: 30px">
          <el-input v-model="form.unit" placeholder="请输入单位" style="width: 100%; margin-right: 10px"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="goodsChangeRecordOpen" width="80%" append-to-body>
      <el-table v-loading="goodsChangeRecordLoading" :data="goodsChangeRecordList" >
<!--        <el-table-column label="操作类型" align="center" prop="typeStr" width="100"/>-->
        <el-table-column label="修改内容" align="center" prop="content" />

        <el-table-column label="操作人" align="center" prop="createBy" width="100"/>
        <el-table-column label="操作时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>




<!--

    <el-dialog :title="title" v-model="openGoodsActivityPrice" width="900px" append-to-body>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAddGoodsActivityPrice" >新增</el-button>
      </el-col>

      <el-table v-loading="goodsActivityPriceLoading" :data="goodsActivityPriceList" >
        <el-table-column label="商户名称" align="center" prop="merchantName" />
        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="开始时间" align="center" prop="beginTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.beginTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="">确 定</el-button>
          <el-button @click="cancelGoodsActivityPrice">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog :title="title" v-model="openAddGoodsActivityPrice" width="600px" append-to-body>

      <el-form ref="goodsActivityPriceRef" :model="goodsActivityPriceForm" :rules="rules" label-width="80px">

        <el-form-item label="商户名称" prop="merchantName">
          <el-select v-model="goodsActivityPriceForm.merchantName" multiple collapse-tags style="margin-left: 20px;"
                     placeholder="请选择" @change="changeMerchantId">
            <el-option v-for="item in merchantArr" :key="item.account" :label="item.account" :value="item.account" />
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input v-model="goodsActivityPriceForm.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="开始时间" prop="beginTime">
          <el-input v-model="goodsActivityPriceForm.beginTime" placeholder="请输入开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-input v-model="goodsActivityPriceForm.endTime" placeholder="请输入结束时间" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitGoodsActivityPriceForm">确 定</el-button>
          <el-button @click="cancelAddGoodsActivityPrice">取 消</el-button>
        </div>
      </template>
    </el-dialog>


-->

    <!-- Detail 组件 -->
    <Detail ref="detailRef" />

    <!-- 导入商品 组件 -->
    <ExportGoodsInfo ref="exportGoodsInfoRef"/>

  </div>
</template>

<script setup name="GoodsInfo">
import { listGoodsInfo, getGoodsInfo, delGoodsInfo, addGoodsInfo, updateGoodsInfo, addShopCartInfo,listTemplatesInfo,
  listBrandsInfo, listCategoryInfo, listLabelInfo, listMerchantLevelInfo, addShopCartBatchs, downLoadImgZip,
  localGet, uploadImgServerMaster, uploadImgServerDetail, hasEmoji, listGoodsChangeRecord, listGoodsActivityPrice,
  listMerchantInfo, operate } from "@/api/business/goodsInfo";
import { getIsAdmin } from "@/api/system/user";
import { getIsManage } from "@/api/system/user";
import goodsAvatar from "./goodsAvatar";
import Detail from './detail.vue';
import ExportGoodsInfo from './exportGoodsInfo.vue';
import {ElMessage} from "element-plus";
import {
  Plus,
  Delete,
} from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance();

const goodsInfoList = ref([]);
const open = ref(false);
const loading = ref(true);

const goodsChangeRecordOpen = ref(false);
const goodsChangeRecordLoading = ref(true);
const goodsChangeRecordList = ref([]);

const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const isAdmin = ref(true);
const total = ref(0);
const title = ref("");
const templateArr = ref([]);//模版list
const brandArr = ref([]);//品牌list
const categoryArr = ref([]);//分类list
const labelArr = ref([]);//标签list
const merchantLevelArr = ref([]);//商品等级list
const levelPriceArr = ref([]);//等级对应价格list
const fileList = ref([]);
const detailFileList = ref([]);
const detailRef = ref(null);

const merchantArr = ref([]);//商品list


const token =  localGet('token') || '';
const tokenDetail =  localGet('token') || '';
const exportGoodsInfoRef = ref(null);

const openGoodsActivityPrice = ref(false);
const goodsActivityPriceList = ref([]);
const goodsActivityPriceLoading = ref(true);


const openAddGoodsActivityPrice = ref(false);

const data = reactive({
  uploadImgServerMaster,
  uploadImgServerDetail,
  token: localGet('token') || '',
  tokenDetail: localGet('token') || '',

  form: {
    businessGoodsActivityPrices:[],
    merchantPriceArr: null
  },

  goodsActivityPriceForm:{
    merchantName:null,
    merchantId:null,
    price: null,
    beginTimeStr : null,
    endTimeStr: null,
  },

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    number: null,
    name: null,
    materialName: null,
    brandName: null,
    categoryName: null,
    labelName: null,
    listStatus: 1,
  },
  rules: {
    code: [{ required: true, message: "商品编码不能为空", trigger: "blur" }],
    number: [{ required: true, message: "商品货号不能为空", trigger: "blur" }],
    name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    costPrice: [{ required: true, message: "成本价不能为空", trigger: "blur" }],
    weight: [{ required: true, message: "商品重量不能为空", trigger: "blur" }],
    templateName: [{ required: true, message: "模板不能为空", trigger: "blur" }],
  },

  searchParams: {
    goodsId: null,
    goodsIdList :[],
    code:null
  },

  searchRecordParams: {
    goodsId: null
  },

  addMerchantParams: {
    merchantIdList: []
  },

  operateParams: {
    id: null,
    menuCode:null
  },

});

const listStatusOptions = ref([
  {
    value: 1,
    label: '上架中'
  },{
    value: 2,
    label: '已下架'
  }
]);

const { queryParams, form, rules, searchParams, searchRecordParams, goodsActivityPriceForm, addMerchantParams, operateParams } = toRefs(data);

/** 查询商户信息列表 */
function getList() {
  loading.value = true;
  listGoodsInfo(queryParams.value).then(response => {
    // response.rows.forEach(item => {
    //   item.goodsCoverImg=[item.goodsCoverImg,item.goodsCoverImg]
    // });
    goodsInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  goodsChangeRecordOpen.value = false;

  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    goodsCoverImg: null,
    goodsCoverImgList: [],
    goodsDetailImgList: [],
    businessGoodsActivityPrices: [],
    code: null,
    number: null,
    name: null,
    materialName: null,
    specs: null,
    price: null,
    weight: null,
    templateId: null,
    templateName: null,
    brandId: null,
    brandName: null,
    categoryId: null,
    categoryName: null,
    labelId: null,
    labelName: null,
    barCode: null,
    unit: null,
    detailContent: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null,
    warehouseName:null,
    costPrice : null,
    priceUrl:null,
    taxRate:null,
    taxCode : null
  };
  proxy.resetForm("goodsInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  let json = {
    merchantName:'',
    price:'',
    beginTimeStr:'',
    endTimeStr:'',
  }
  form.value.businessGoodsActivityPrices.push(json)
  fileList.value = [];
  detailFileList.value = [];
  title.value = "添加商品信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getGoodsInfo(_id).then(response => {

    merchantLevelArr.value = response.data.merchantLevelList;
    fileList.value = [];
    detailFileList.value = [];
    response.data.goodsCoverImgList.forEach(url => fileList.value.push({url}));
    response.data.goodsDetailImgList.forEach(url => detailFileList.value.push({url}));

    form.value = response.data;
    open.value = true;
    title.value = "修改商品信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsInfoRef"].validate(valid => {
    if (valid) {
      // form.value.businessGoodsActivityPrices.forEach((item) => {
      //   item.beginTimeStr = new Date(item.beginTime);
      //   item.endTimeStr = new Date(item.endTime);
      //
      //
      //   item.beginTime = null;
      //   item.endTime = null;
      // })
      const params = {
        ...form.value,
        merchantLevelArr:merchantLevelArr.value,
        goodsCoverImgList:fileList.value.map(item => item.url),

        goodsDetailImgList:detailFileList.value.map(item => item.url)
      }
      if (form.value.id != null) {
        updateGoodsInfo(params).then(response => {

          if (response.resultCode === 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.message)
          }


        });
      } else {
        addGoodsInfo(params).then(response => {

          if (response.resultCode === 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.message)
          }


        });
      }
    }
  });
}

//批量导入
function exportGoodsInfoExcel() {
  if (exportGoodsInfoRef.value) exportGoodsInfoRef.value.init(ids.value);
}



/** 介入购物车 */
function addShopCart(row) {
  const goodsId = row.id ;
  searchParams.value.goodsId = goodsId;
  proxy.$modal.confirm('是否确认加入购物车？').then(function() {
    return addShopCartInfo(searchParams.value);
  }).then(() => {
    proxy.$modal.msgSuccess("加入成功");
  }).catch(() => {});

}

function addShopCartBatch() {
  const _ids = ids.value

  proxy.$modal.confirm('是否确认加入购物车？').then(function() {
    return addShopCartBatchs(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("加入成功");
  }).catch(() => {});
}

function downLoadImg(row) {
  const goodsId = row.id ;
  searchParams.value.goodsId = goodsId;
  const code = row.code ;
  const name = row.name ;
  searchParams.value.code = code;
  proxy.$modal.confirm('是否确认下载素材？').then(function() {

    downLoadImgZip(searchParams.value).then(response => {

      const urlPath = response;
      // window.open(urlPath, '_blank');

      const a = document.createElement('a');
      a.href = urlPath;
      a.download = name +' 图片素材.zip'; // 设置下载文件名（可选）
      document.body.appendChild(a);
      a.click(); // 触发点击下载
      document.body.removeChild(a);

    });
  }).then(() => {
    getList();
  }).catch(() => {});
}

/** 查询商户的信用额度记录 */
function goodsChangeRecord(row) {
  goodsChangeRecordOpen.value = true;

  const goodsId = row.id;
  searchRecordParams.value.goodsId = goodsId;

  goodsChangeRecordLoading.value = true;

  listGoodsChangeRecord(searchRecordParams.value).then(response => {
    goodsChangeRecordList.value = response.rows;
    goodsChangeRecordLoading.value = false;
  });
}

const imgZipDownLoad = (row) => {

  const zipFilUrl = row.zipUrl ;
  const goodsId = row.id ;

  const link = document.createElement('a');
  link.href = zipFilUrl;
  link.download = goodsId + '图片.zip'; // 可以指定下载后的文件名
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};



/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除该商品？').then(function() {
    return delGoodsInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 删除按钮操作 */
function goodsOperate(row, menuCode) {

  const id = row.id;

  operateParams.value.id = id;
  operateParams.value.menuCode = menuCode;

  proxy.$modal.confirm('是否确认？').then(function() {
    return operate(operateParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});

}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/goodsInfo/export', {
    ...queryParams.value
  }, `商品_${new Date().getTime()}.xlsx`)
}


/** 查询商户信息列表 */
function getTemplateList() {
  listTemplatesInfo().then(response => {
    templateArr.value = response.rows;
  });
}

function templateChange(name){

  for (let i = 0; i < templateArr.value.length; i++) {
    if (templateArr.value[i].name === name) {

      console.log("name---" +name)
      console.log("id---" + templateArr.value[i].id)
      form.templateName = name;
      form.value.templateId = templateArr.value[i].id;
    }
  }
}
/** 查询商户信息列表 */
function getBrandList() {
  listBrandsInfo().then(response => {
    brandArr.value = response.rows;
  });
}

function brandChange(name){

  for (let i = 0; i < brandArr.value.length; i++) {
    if (brandArr.value[i].name === name) {

      form.brandName = name;
      form.value.brandId = brandArr.value[i].id;
    }
  }
}

/** 查询商户信息列表 */
function getCategoryList() {
  listCategoryInfo().then(response => {
    categoryArr.value = response.rows;
  });
}

function categoryChange(name){
  for (let i = 0; i < categoryArr.value.length; i++) {
    if (categoryArr.value[i].name === name) {

      form.categoryName = name;
      form.value.categoryId = categoryArr.value[i].id;
    }
  }
}
/** 查询商户信息列表 */
function getLabelList() {
  listLabelInfo().then(response => {
    labelArr.value = response.rows;
  });
}

function labelChange(name){
  for (let i = 0; i < labelArr.value.length; i++) {
    if (labelArr.value[i].name === name) {
      form.labelName = name;
      form.value.labelId = labelArr.value[i].id;
    }
  }
}

/** 查询商户等级信息列表 */
function getMerchantLevelList() {
  listMerchantLevelInfo().then(response => {
    merchantLevelArr.value = response.rows;
  });
}

/** 查询商户信息列表 */
function getMerchantList() {
  listMerchantInfo().then(response => {
    merchantArr.value = response.rows;
  });
}


function getRoleForAdmin() {
  // getIsAdmin().then(response => {
  getIsManage().then(response => {

    isAdmin.value = response;
  });
}

function handlePrice(price, index, id, name,item) {

  console.log("---price--", price)

  let costPrice = form.value.costPrice;
  let profitRate = 100;

  if(costPrice === null){
    profitRate = 0;
  }else{
    profitRate = (price - costPrice)/costPrice * 100
  }

  levelPriceArr.value = [];

  merchantLevelArr.value[index].profitRate = profitRate;

  levelPriceArr.value.push(
      {
        id : id,
        price :price,
        name : name,
        profitRate : profitRate
      }
  )

  console.log("levelPriceArr", levelPriceArr.value)

}


function handleCostPrice(costPrice) {

  console.log("---costPrice--", costPrice)

  levelPriceArr.value = [];

  for (let i = 0; i < merchantLevelArr.value.length; i++) {

    let price = merchantLevelArr.value[i].price

    let profitRate = (price - costPrice)/costPrice * 100

    levelPriceArr.value.push(
        {
          id : merchantLevelArr.value[i].id,
          price :merchantLevelArr.value[i].price,
          name : merchantLevelArr.value[i].name,
          profitRate : profitRate
        }
    )

    merchantLevelArr.value[i].profitRate = profitRate;
  }
}


function handleBeforeUpload(file){
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
function handleRemove(file){
  let url=file.response?.url || file.url
  const index = fileList.value.indexOf(url);
  if (index !== -1) fileList.value.splice(index, 1);
}
function handleUrlSuccess (file){
  if(file.code===200) fileList.value.push({url: file.url});
}


function handleBeforeUploadDetail(file){
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
function handleRemoveDetail(file){
  let url=file.response?.url || file.url
  const index = detailFileList.value.indexOf(url);
  if (index !== -1) detailFileList.value.splice(index, 1);
}
function handleUrlSuccessDetail (file){
  if(file.code===200) detailFileList.value.push({url: file.url});
}

// 详情
function openDetail(id) {
  if (detailRef.value) detailRef.value.init(id);
}

function rowClick(row,column,event) {
  if (detailRef.value) detailRef.value.init(row.id);
}


function goodsActivityPriceDetail(id) {

  goodsActivityPriceList.value = [];
  openGoodsActivityPrice.value = true;
  goodsActivityPriceLoading.value = false;

  if(id != null || id != undefined){

    openGoodsActivityPrice.value = true;
    goodsActivityPriceLoading.value = true;

    listGoodsActivityPrice(id).then(response => {

      goodsActivityPriceList.value = response.rows;
      goodsActivityPriceLoading.value = false;
    });
  }

  title.value = "添加活动价格";
}

function cancelGoodsActivityPrice() {
  openGoodsActivityPrice.value = false;
}

function handleAddGoodsActivityPrice() {
  openAddGoodsActivityPrice.value = true;
  title.value = "新增活动价格明细";
}

const handleAddCol = () => {
  let json = {
    merchantName:'',
    price:'',
    beginTime:'',
    endTIme:'',
  }
  form.value.businessGoodsActivityPrices.push(json)
}

const handleDeleteCol = (index) => {
  form.value.businessGoodsActivityPrices.splice(index,1)
}



const changeMerchantId =(value)=>{
  if(test.isEmpty(value)){
    addMerchantParams.merchantIdList = undefined
  }else{
    addMerchantParams.merchantIdList = value.map(item=>item.id).join(',')
  }
}

/** 提交按钮 */
function submitGoodsActivityPriceForm() {


  goodsActivityPriceList.value.push(


  )

}

function cancelAddGoodsActivityPrice() {
  openAddGoodsActivityPrice.value = false;
  resetAddGoodsActivityPrice();
}

function resetAddGoodsActivityPrice() {
  goodsActivityPriceForm.value = {
    merchantName: null,
    merchantId: null,
    price: null,
    beginTime: null,
    endTime: null
  };
  proxy.resetForm("goodsActivityPriceRef");
}

getList();
getTemplateList();
getBrandList();
getCategoryList();
getLabelList();
getMerchantLevelList();
getRoleForAdmin();
getMerchantList();

</script>


<style scoped>
.add {
  display: flex;
}
.add-container {
  flex: 1;
  height: 100%;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}

.plus-icon{
  font-size: 28px;
  color: #8c939d;
  font-weight: 400;
}

.el-image-viewer_wrapper{
  z-index: 20028 !important;
}
</style>
